package com.ruoyi.web.controller.common;

import java.io.IOException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.view.RedirectView;
import com.ruoyi.common.annotation.Anonymous;
import javax.servlet.http.HttpServletResponse;

/**
 * 处理域名根路径的请求
 * 特别是用于接收微信授权回调
 */
@RestController
@RequestMapping("/")
public class RootCallbackController {

    /**
     * 处理微信授权回调
     * 将回调请求根据state参数重定向到实际的处理路径
     */
    @Anonymous
    @GetMapping("/")
    public RedirectView handleWxCallback(@RequestParam("code") String code,
            @RequestParam("state") String state,
            HttpServletResponse response) throws IOException {
        System.out.println("接收到微信根路径回调 - code: " + code + ", state: " + state);

        // 从state中解析uuid和path
        String uuid = "";
        String path = "";

        if (state != null && state.contains("uuid=") && state.contains("path=")) {
            String[] parts = state.split("&");
            for (String part : parts) {
                if (part.startsWith("uuid=")) {
                    uuid = part.substring(5);
                } else if (part.startsWith("path=")) {
                    path = part.substring(5);
                }
            }
        }

        System.out.println("解析state - uuid: " + uuid + ", path: " + path);

        // 构建重定向URL
        String redirectUrl = "/" + path + "?code=" + code + "&state=" + uuid;
        System.out.println("重定向到: " + redirectUrl);

        return new RedirectView(redirectUrl);
    }
}